﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using System.ComponentModel;
using DataAccess;
using BusinessObjects;
using Toolkit;
using DCMSExceptions;
using System.Data;

namespace BusinessLogic {
  /// <summary>
  /// Business Logic Layer for child diary
  /// </summary>
  public class DiaryBll : IDiaryLogic {

    private DiaryDal dal = new DiaryDal( );

    #region - Public methods -

    /// <summary>
    /// Gets the diary on date.
    /// </summary>
    /// <param name="date">The date.</param>
    /// <returns></returns>
    public BindingList<ChildDiary> GetDiaryOnDate( DateTime date ) {
      BindingList<ChildDiary> diary;
      try {
        diary = dal.GetDiaryOnDate( date );
      } catch ( DataException ex ) {
        throw new BusinessException( "Fout bij ophalen van dagboek.", ex );
      }
      return diary;
    }

    /// <summary>
    /// Saves the specified diary.
    /// </summary>
    /// <param name="diary">The diary.</param>
    public void Save( BusinessObjects.ChildDiary diary ) {
      if ( Validate( diary ) ) {
        try {
          dal.Save( diary );
        } catch ( Exception ex ) {
          throw new BusinessException( ex.Message, ex );
        }
      } else {
        throw new BusinessException( "Fout bij bewaren. \n" + diary.BrokenRulesMessages );
      }

    }

    /// <summary>
    /// Deletes the specified diary.
    /// </summary>
    /// <param name="diary">The diary.</param>
    public void Delete( ChildDiary diary ) {
      try {
        dal.Delete( diary );
      } catch ( Exception ex ) {
        throw new BusinessException( ex.Message, ex );
      }
    }

    #endregion

    private bool Validate( ChildDiary diary ) {
      diary.ClearBrokenRules( );

      if ( diary.IsArrivalTimeEmpty( ) ) {
        diary.AddBrokenRule( "ArrivalTime", "Geen aankomst tijd." );
      }

      if ( !diary.IsArrivalTimeEmpty( ) && !diary.IsDepartureTimeEmpty( ) ) {
        TimeSpan fromTime = TimeSpan.Parse( diary.ArrivalTime );
        TimeSpan toTime = TimeSpan.Parse( diary.DepartureTime );
        if ( toTime <= fromTime ) {
          diary.AddBrokenRule( "TimeRange", "Vertrek uur is kleiner dan aankomst uur." );
        }
      }
      return diary.IsValid;
    }

  }
}
